mini.parse();

function ArticlesFormHandler() {
};

ArticlesFormHandler.instance = new ArticlesFormHandler();

// 获得全局的文章数据表格对象
ArticlesFormHandler.articlesForm = new mini.Form("articlesForm");

ArticlesFormHandler.formData = {};

// 文章状态数据
ArticlesFormHandler.baiStateData = [
	{text: "有效",value: 1},
	{text: "无效",value: 0}
];
mini.get("baiState").setData(ArticlesFormHandler.baiStateData);

// 编辑器关联表单Id
ArticlesFormHandler.baiDetailId = "baiDetail_bat";
// 全局附件名，用于检测相同附件名称是否存在
ArticlesFormHandler.g_attachName = "";
// 全局id
ArticlesFormHandler.g_baiId = null;
//文章附件文件上传类型
ArticlesFormHandler.fileTypes = "*.gif;*.jpg;*.png;*.bmp;*.rar;*.zip;*.jar;*.iso;*.tar";
//创建上传文章附件控件
SWFUploadTools.createSWFUBtn(__realpath+__articleAttachPath, ArticlesFormHandler.fileTypes, "upload_baiAttach", uploadBauSuccess);

try {
	var baiDetailEditor = KindEditor.create('#' + ArticlesFormHandler.baiDetailId,
			{
				resizeType : 0,
				uploadJson : "../../resource/kindeditor/jsp/upload_json.jsp?imgDir="+ __articleImgPath,
				fileManagerJson : '../../resource/kindeditor/jsp/file_manager_json.jsp',
				allowPreviewEmoticons : false,
				allowImageUpload : true,
				items : ['undo', 'redo', '|', 'fontname', 'fontsize', '|',
						'forecolor', 'hilitecolor', 'bold', 'italic',
						'underline', 'removeformat', '|', 'justifyleft',
						'justifycenter', 'justifyright', 'insertorderedlist',
						'insertunorderedlist', '|', 'emoticons', 'image',
						'multiimage', 'link', 'unlink', '|', 'table', 'hr',
						'pagebreak', '|', 'source', 'preview', 'fullscreen']
			});
} catch (e) {
}

/**
 * 标准方法接口定义
 * 
 * @param {}
 *            data
 */
ArticlesFormHandler.passData = function(data) {
	if (data.action == "edit") {
		// 跨页面传递的数据对象，克隆后才可以安全使用
		data = mini.clone(data);
		ArticlesFormHandler.formData.baiId = data.baiId;

		$.ajax({
			url : __root + "/getBaiById.do?baiId=" + data.baiId,
			cache : false,
			dataType : 'json',
			success : function(text) {			
				//设置全局id
            	ArticlesFormHandler.g_baiId = data.baiId;
				ArticlesFormHandler.articlesForm.setData(text);	
				ArticlesFormHandler.g_attachName = text.baiAttachname;
				
				if(text.baiImage != null && text.baiImage != ""){
					mini.get("delBaiImageBtn").enable();
				}
				
				if (text.baiDetail != "") {
					baiDetailEditor.html(text.baiDetail);
				}
				
				if(text.baiImage != ""){
					mini.get("upload_baiImage").setText(text.baiImage);
					
					$("#baiImageViewer").empty();
					var iframe = "<iframe src='"+ __root +"/imgViewerContorller.do?basePath="+__realpath+__articleImgPath+"&newImgPath=" + text.baiImage + "' frameborder='0' border='0' style='margin:0;padding:0;width:100%;height:100%;'/>";
					$("#baiImageViewer").append(iframe);
				}
			}
		});
	}else{
		// 默认文章状态为有效
    	mini.get("baiState").setValue(1);
	} 
}

/**
 * 保存（新增或编辑）文章信息
 */
ArticlesFormHandler.saveArticleInfo = function() {
	var articlesFormData = ArticlesFormHandler.articlesForm.getData(true);
	articlesFormData.baiId = ArticlesFormHandler.formData.baiId;

	ArticlesFormHandler.articlesForm.validate();
	if (ArticlesFormHandler.articlesForm.isValid() == false)
		return;
		
	if (baiDetailEditor.html().length > 0) {
		articlesFormData.baiDetail = baiDetailEditor.html();
	}
	
	var json = mini.encode(articlesFormData);
	
	if((articlesFormData.baiId == null || articlesFormData.baiId == "" 
			|| ArticlesFormHandler.g_attachName != articlesFormData.baiAttachname)
				&& (articlesFormData.baiAttachurl != "")){
		$.ajax({
			url : __root + "/isExistingFileName.do",
			type : "POST",
			data : {
				v_baiId: articlesFormData.baiId,
				v_attachName: articlesFormData.baiAttachname,
				v_attachUrl: articlesFormData.baiAttachurl
			},
			cache : false,
			dataType: 'json',
			success : function(text) {
				if(text.warning != null && text.warning != "" 
						&& text.warning != "undefined"){
					MiniuiTools.miniWarning("系统提示", text.warning);
					return;
				}
				
				ArticlesFormHandler.doSaveArticleInfo(json);
			},
			error : function(jqXHR, textStatus, errorThrown) {
				MiniuiTools.miniError("系统提示", jqXHR.responseText, function(){
	            	ArticlesFormHandler.closeCurrentWin();
	            });
			}
		});
	}else{
		ArticlesFormHandler.doSaveArticleInfo(json);
	}
}

/**
 * 执行保存文章信息操作
 * @param {} json
 */
ArticlesFormHandler.doSaveArticleInfo = function(json){
	$.ajax({
		url : __root + "/saveOrUpdateBai.do",
		type : "POST",
		data : {
			articleInfo : json,
			lslUser: gbOperateUser,
    		lslAddress: gbOperateIp
		},
		cache : false,
		dataType: 'text',
		success : function(info) {
			MiniuiTools.miniInfo("系统提示","保存成功！", function(action){
        		ArticlesFormHandler.closeCurrentWin("save");
        	});
		},
		error : function(jqXHR, textStatus, errorThrown) {
			MiniuiTools.miniError("系统提示", jqXHR.responseText, function(){
            	ArticlesFormHandler.closeCurrentWin();
            });
		}
	});
}

/**
 * 删除文章图片
 */
ArticlesFormHandler.delBaiImage = function(){
	var baiId = ArticlesFormHandler.g_baiId;
	var baiImage = ArticlesFormHandler.articlesForm.getData().baiImage;
	
	if(baiId != null && baiId != "" && baiImage != null && baiImage != ""){
		$.ajax({
	        url: __root + "/delBaiImageById.do",
	        type: "POST",
	        data: {
	        	baiId: baiId,
	        	lslUser: gbOperateUser,
    			lslAddress: gbOperateIp
	        },
	        cache: false,
	        success: function (text) {
	        	 MiniuiTools.miniInfo("系统提示","删除成功！");
	        	 //清空浏览框
	        	 mini.get("upload_baiImage").setText(null);
	        	 //重新为隐藏表单设置值
               	 mini.get("hidden_baiImage").setValue(null);
               	 //清空预览框
               	 $("#baiImageViewer").empty();
				 
	        },
	        error: function (jqXHR, textStatus, errorThrown) {
	        	MiniuiTools.miniError("系统提示", jqXHR.responseText);
	        }
	    });
	}else{
		MiniuiTools.miniWarning("系统提示","没有可删除的图片资源！");
	}
}

/**
 * 处理上传成功的文章图片
 * @param {} e
 */
ArticlesFormHandler.showbaiImage = function(e){
	MiniuiTools.miniInfo("系统提示","图片上传成功！");
	var fdata = mini.decode(e.serverData);
	var newPath = fdata.imgPath;
	$("#baiImageViewer").empty();
	
	var iframe = "<iframe src='"+ __root +"/imgViewerContorller.do?basePath="+__realpath+__articleImgPath+"&newImgPath=" + newPath + "' frameborder='0' border='0' style='margin:0;padding:0;width:100%;height:100%;'/>";
	$("#baiImageViewer").append(iframe);
	
	mini.get("hidden_baiImage").setValue(newPath);
}

/**
 * 关闭窗口
 * 
 * @param {}
 *            action
 */
ArticlesFormHandler.closeCurrentWin = function(action) {
	if (window.CloseOwnerWindow)
		window.CloseOwnerWindow(action);
	else
		window.close();
		
	ArticlesFormHandler.g_baiId = null;
}

ArticlesFormHandler.closeMiniWin = function() {
	ArticlesFormHandler.closeCurrentWin("cancel");
	ArticlesFormHandler.g_baiId = null;
}

/**
 * 窗体最大化按钮点击监听事件
 */
ArticlesFormHandler.onMaxAction = function(){
	var baiImageViewer = document.getElementById("baiImageViewer");
	if(baiImageViewer.style.height == "290px"){
		baiImageViewer.style.width = "98%";
		baiImageViewer.style.height = "360px";
	}else{
		baiImageViewer.style.width = "638px";
		baiImageViewer.style.height = "290px";
	}
}

/**
 * 处理上传成功后的文章附件
 * @param {} file
 * @param {} serverData
 */
function uploadBauSuccess(file, serverData) {
	MiniuiTools.miniHideLoading();
	MiniuiTools.miniInfo("系统提示","文件上传成功！");
	
	var fdata = mini.decode(serverData);
	mini.get("baiAttachurl").setValue(fdata.imgPath);
	mini.get("baiAttachname").setValue(fdata.imgName);
}

function validBagName(e){
	if(e.value == "" || e.value == "-1"){
		e.errorText = "请选择文章分类！";
        e.isValid = false;
	}
}

function validBagName(e){
	if(e.value == ""){
		e.errorText = "文章排序不能为空！";
        e.isValid = false;
	}
}